﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;


namespace FSO
{
    public partial class FormCalendarPlan : Form, InterfaceObjDeleteableForm
    {
        private DataSetFSO.CALENDAR_PLANRow _rowCalendarPlan;
        int _RootNodeTag = -100;
        private bool _isNew;
        int countModifiedItems = 0;
		public bool AllowSave;

        public FormCalendarPlan(int? pid)
        {

            InitializeComponent();

            _isNew = true;

            _rowCalendarPlan = dataSetFSO1.CALENDAR_PLAN.NewCALENDAR_PLANRow();

            _rowCalendarPlan.START_DATE = DateTime.Now.Date;
            _rowCalendarPlan.END_DATE = DateTime.Today.AddYears(1);

            dataSetFSO1.CALENDAR_PLAN.AddCALENDAR_PLANRow(_rowCalendarPlan);

            DataSetFSO.CONTRACTRow contrRow = contractTableAdapter1.GetDataByPID(pid.Value).First();
            contractTableAdapter1.FillByID(dataSetFSO1.CONTRACT, contrRow.ID);
            _rowCalendarPlan.CONTRACTRow = dataSetFSO1.CONTRACT.FindByID(contrRow.ID);

            _rowCalendarPlan.PID = pid.Value;
           
        }

        public FormCalendarPlan(DataSetFSO.CALENDAR_PLANRow rowCalendarPlan)
        {
            InitializeComponent();

            _isNew = false;

            calendaR_PLANTableAdapter1.FillById(dataSetFSO1.CALENDAR_PLAN, rowCalendarPlan.ID);
            _rowCalendarPlan = dataSetFSO1.CALENDAR_PLAN.FindByID(rowCalendarPlan.ID);

            contractTableAdapter1.FillByID(dataSetFSO1.CONTRACT, _rowCalendarPlan.CONTRACT_ID);

            this.Text = "Календарный план " + _rowCalendarPlan.NUMBER;

        }

        public void BindControlsClalendarPlan()
        {
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _rowCalendarPlan, dataSetFSO1.CALENDAR_PLAN.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            radDateTimePickerStartDate.DataBindings.Clear();
            radDateTimePickerStartDate.DataBindings.Add("Value", _rowCalendarPlan, dataSetFSO1.CALENDAR_PLAN.START_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            radDateTimePickerEndDate.DataBindings.Clear();
            radDateTimePickerEndDate.DataBindings.Add("Value", _rowCalendarPlan, dataSetFSO1.CALENDAR_PLAN.END_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            if (_rowCalendarPlan.CONTRACTRow !=null)
            {
                radLabelContract.DataBindings.Clear();
                radLabelContract.DataBindings.Add("Text", _rowCalendarPlan.CONTRACTRow, dataSetFSO1.CONTRACT.NUMBERColumn.ColumnName, false, DataSourceUpdateMode.Never, "<Не указан>");
            }
            else
            {
                radLabelContract.Text = "<Не указан>";
            }
        }

        public void BindControlsCPStage()
        {
            if ((System.Int32)radTreeViewStages.SelectedNode.Tag != _RootNodeTag)
            {
                SetControlsVisible(true);

                DataSetFSO.CP_STAGERow selectedStage = (DataSetFSO.CP_STAGERow)((DataRowView)radTreeViewStages.SelectedNode.DataBoundItem).Row;
                if (selectedStage != null)
                {
                    radTextBoxStageNumber.DataBindings.Clear();
                    radTextBoxStageNumber.DataBindings.Add("Text", selectedStage, dataSetFSO1.CP_STAGE.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

                    radDateTimePickerStageStartDate.DataBindings.Clear();
                    radDateTimePickerStageStartDate.DataBindings.Add("Value", selectedStage, dataSetFSO1.CP_STAGE.START_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

                    radDateTimePickerStageEndDate.DataBindings.Clear();
                    radDateTimePickerStageEndDate.DataBindings.Add("Value", selectedStage, dataSetFSO1.CP_STAGE.END_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

                    radLabelStageCaption.Text = "Этап № " + selectedStage.NUMBER + ". " + selectedStage.NAME;
                }
            }
            else if ((System.Int32)radTreeViewStages.SelectedNode.Tag == _RootNodeTag)
            {
                SetControlsVisible(false);
            }
        }

        public void DesignGridProduct(int stageId)
        {         


            radGridViewProducts.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            //radGridViewProducts.MultiSelect = true;

            GridViewTextBoxColumn colProdName = new GridViewTextBoxColumn(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NAMEColumn.ColumnName);
            colProdName.HeaderText = "Наименование";
            colProdName.ReadOnly = true;

            GridViewDecimalColumn colCount = new GridViewDecimalColumn(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.COUNTColumn.ColumnName);
            colCount.HeaderText = "Количество";
            colCount.DecimalPlaces = 0;
            colCount.Minimum = 1;

            GridViewTextBoxColumn colMeter = new GridViewTextBoxColumn(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NSI_METER_NAMEColumn.ColumnName);
            colMeter.HeaderText = "Ед. Измерения";
            colMeter.ReadOnly = true;

            GridViewCheckBoxColumn colType = new GridViewCheckBoxColumn(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.TYPEColumn.ColumnName);
            colType.HeaderText = "Товар";
            colType.ReadOnly = true;

            GridViewTextBoxColumn colCPStageId = new GridViewTextBoxColumn(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.CP_STAGE_IDColumn.ColumnName);

            radGridViewProducts.MasterTemplate.Columns.Clear();
            radGridViewProducts.MasterTemplate.Columns.Add(colProdName);
            radGridViewProducts.MasterTemplate.Columns.Add(colCount);
            radGridViewProducts.MasterTemplate.Columns.Add(colMeter);
            radGridViewProducts.MasterTemplate.Columns.Add(colType);
            radGridViewProducts.MasterTemplate.Columns.Add(colCPStageId);

            colCPStageId.IsVisible = false;           

            colCount.AllowFiltering = true;
            CompositeFilterDescriptor compositeFilter = new CompositeFilterDescriptor();
            compositeFilter.FilterDescriptors.Add(new FilterDescriptor(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.CP_STAGE_IDColumn.ColumnName, FilterOperator.IsEqualTo, stageId));
            radGridViewProducts.FilterDescriptors.Add(compositeFilter);

            radGridViewProducts.EnableSorting = true;
            radGridViewProducts.MasterTemplate.EnableGrouping = true;
            radGridViewProducts.EnableGrouping = false;
            SortDescriptor type = new SortDescriptor(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.TYPEColumn.ColumnName, ListSortDirection.Descending);
            SortDescriptor name = new SortDescriptor(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NAMEColumn.ColumnName, ListSortDirection.Ascending);
            radGridViewProducts.SortDescriptors.Add(type);            
            radGridViewProducts.SortDescriptors.Add(name);

            radGridViewProducts.MasterTemplate.DataSource = dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES;           
        }

        public void DesignTreeViewStages()
        {
            radTreeViewStages.DisplayMember = dataSetFSO1.CP_STAGE.NAMEColumn.ColumnName;
            radTreeViewStages.ValueMember = dataSetFSO1.CP_STAGE.IDColumn.ColumnName;
            radTreeViewStages.ParentIDMember = dataSetFSO1.CP_STAGE.PARENT_STAGE_IDColumn.ColumnName;
            radTreeViewStages.DataSource = null;
            radTreeViewStages.DataSource = dataSetFSO1.CP_STAGE;
            radTreeViewStages.SetImagesInFill(true);
            radTreeViewStages.VerticalScroll.Enabled = true;
            radTreeViewStages.HorizontalScroll.Enabled = true;
            SetImages(radTreeViewStages.Nodes);            
            
            //Создание фиктивного корневого элемента для реализации добавления нового корневого этапа
            RadTreeNode root = new RadTreeNode("Этапы", true);
            root.Tag = _RootNodeTag;
            root.ImageIndex = 3;
            radTreeViewStages.Nodes.Add(root);

            while (radTreeViewStages.Nodes.Count > 1)
            {
                RadTreeNode tmp = radTreeViewStages.Nodes[0];
                if ((System.Int32)tmp.Tag == _RootNodeTag)
                    tmp = radTreeViewStages.Nodes[1];
                root.Nodes.Add(tmp);
            }
        }

        void SetImages(RadTreeNodeCollection NodesCollection)
        {
            foreach (RadTreeNode node in NodesCollection)
            {
                node.ImageIndex = 0;
                node.SelectedImageIndex = 2;
                node.StateImageIndex = 1;

                if (node.Nodes.Count > 0)
                {
                    foreach (RadTreeNode childNode in node.Nodes)
                    {
                        SetImages(node.Nodes);
                    }
                }
            }
        }

        private void SetControlsVisible(bool visible)
        {
            radTextBoxStageNumber.Visible = visible;
            radDateTimePickerStageStartDate.Visible = visible;
            radDateTimePickerStageEndDate.Visible = visible;
            radLabelStageCaption.Visible = visible;
            radLabelStageNumber.Visible = visible;
            radLabelStageStartDate.Visible = visible;
            radLabelStageEndDate.Visible = visible;
        }

        private void SetControlEnabled(bool enabled)
        {
            radMenuTreeView.Visible = enabled;            
            radMenuGridView.Visible = enabled;
        }

        public void DeleteInvoiceOutItems(int productUnitID)
        {
            invoicE_OUT_ITEMTableAdapter1.ClearBeforeFill = false;
            invoicE_OUT_ITEMTableAdapter1.FillByProductUnitId(dataSetFSO1.INVOICE_OUT_ITEM, productUnitID);
            invoicE_OUT_ITEMTableAdapter1.ClearBeforeFill = true;

            invoicE_OUTTableAdapter1.ClearBeforeFill = false;
            foreach (DataSetFSO.INVOICE_OUT_ITEMRow rowItem in dataSetFSO1.INVOICE_OUT_ITEM)
            {
                if (rowItem.RowState != DataRowState.Deleted)
                {
                    //MessageBox.Show("Inv" + rowItem.ID.ToString());
                    invoicE_OUTTableAdapter1.FillByInvoiceOutItem(dataSetFSO1.INVOICE_OUT, rowItem.INVOICE_OUT_ID);                    
                    rowItem.Delete();                    
                }
            }
            invoicE_OUTTableAdapter1.ClearBeforeFill = true;            
        }

        public string ModifiedInvoiceOut()
        {
            string result ="Счета:";            

            foreach (DataSetFSO.INVOICE_OUTRow rowInvoice in dataSetFSO1.INVOICE_OUT)
            {
                result += "\n" + "№ " + rowInvoice.NUMBER.ToString();
                countModifiedItems++;
            }            

            dataSetFSO1.INVOICE_OUT.Clear();

            return result;
        }

        public void DeletePaymentInItems(int productUnitID)
        {
            paymenT_IN_ITEMTableAdapter1.ClearBeforeFill = false;
            paymenT_IN_ITEMTableAdapter1.FillByProductUnitID(dataSetFSO1.PAYMENT_IN_ITEM, productUnitID);
            paymenT_IN_ITEMTableAdapter1.ClearBeforeFill = true;

            paymenT_INTableAdapter1.ClearBeforeFill = false;
            foreach (DataSetFSO.PAYMENT_IN_ITEMRow rowItem in dataSetFSO1.PAYMENT_IN_ITEM)
            {
                if (rowItem.RowState != DataRowState.Deleted)
                {
                    //MessageBox.Show("Pay" + rowItem.ID.ToString());
                    paymenT_INTableAdapter1.FillByPaymentInItem(dataSetFSO1.PAYMENT_IN, rowItem.PAYMENT_IN_ID);
                    rowItem.Delete();                    
                }
            }
            paymenT_INTableAdapter1.ClearBeforeFill = true;
        }

        public string ModifiedPaymentIn()
        {
            string result = "Платежные поручения:";

            foreach (DataSetFSO.PAYMENT_INRow rowPayment in dataSetFSO1.PAYMENT_IN)
            {
                result += "\n" + "№ " + rowPayment.NUMBER.ToString();
                countModifiedItems++;
            }

            dataSetFSO1.PAYMENT_IN.Clear();

            return result;
        }


        #region IntefaceObjectForm Members
        
        public int Save()
        {
            int nRowsUpdatedCount = -1;

            string resultInformation = "В следствие сохранения были изменены: ";

            if (_rowCalendarPlan.IsNUMBERNull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"№\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                nRowsUpdatedCount = calendaR_PLANTableAdapter1.Update(_rowCalendarPlan);

                dataSetFSO1.PRODUCT_UNIT.Clear();

                producT_UNITTableAdapter1.ClearBeforeFill = false;
                
                foreach (DataSetFSO.CP_STAGERow stageRow in dataSetFSO1.CP_STAGE)
                {
                    //Работа с удаленными этапами
                    //======================================================================================================================================
                    if (stageRow.RowState == DataRowState.Deleted)
                    {
                        int stageRowId = (int)stageRow[dataSetFSO1.CP_STAGE.IDColumn, DataRowVersion.Original];
                        //stageRow.RejectChanges();

                        producT_UNITTableAdapter1.FillByCPStageID(dataSetFSO1.PRODUCT_UNIT, stageRowId);

                        List<DataSetFSO.PRODUCT_UNITRow> productUnitRows = new List<DataSetFSO.PRODUCT_UNITRow>();
                        productUnitRows.Clear();
                        productUnitRows = (from unitRow in dataSetFSO1.PRODUCT_UNIT where (unitRow.RowState != DataRowState.Deleted && unitRow.CP_STAGE_ID == stageRowId) select unitRow).ToList();
                        
                        foreach (DataSetFSO.PRODUCT_UNITRow delRowProductUnit in productUnitRows)
                        {
                            DeleteInvoiceOutItems(delRowProductUnit.ID);
                            DeletePaymentInItems(delRowProductUnit.ID);
                            delRowProductUnit.Delete();
                        }

                        //stageRow.Delete();
                    }
                    //======================================================================================================================================
                    else
                    {
                        producT_UNITTableAdapter1.FillByCPStageID(dataSetFSO1.PRODUCT_UNIT, stageRow.ID);
                    }
                }
                producT_UNITTableAdapter1.ClearBeforeFill = true;

                nRowsUpdatedCount += cP_STAGETableAdapter1.Update(dataSetFSO1.CP_STAGE);

                foreach (DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow row in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                        for (int i = 0; i < row.COUNT; i++)
                        {
                            DataSetFSO.PRODUCT_UNITRow tmpProduct = dataSetFSO1.PRODUCT_UNIT.NewPRODUCT_UNITRow();
                            tmpProduct.TYPE = row.TYPE;
                            tmpProduct.NAME = row.NAME;
                            tmpProduct.CP_STAGE_ID = row.CP_STAGE_ID;
                            tmpProduct.PID = _rowCalendarPlan.PID;
                            if (!row.IsNSI_PRODUCT_IDNull())
                                tmpProduct.NSI_PRODUCT_ID = row.NSI_PRODUCT_ID;

                            dataSetFSO1.PRODUCT_UNIT.AddPRODUCT_UNITRow(tmpProduct);
                        }
                    }
                    else if (row.RowState == DataRowState.Modified)
                    {
                        int newCount = row.COUNT;

                        //row.RejectChanges();

                        int oldCount = (int) row[dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.COUNTColumn, DataRowVersion.Original];

                        //MessageBox.Show(oldCount.ToString() + oldCount2.ToString());

                        int dCount = newCount - oldCount;

                        if (dCount < 0)
                        {
                            List<DataSetFSO.PRODUCT_UNITRow> productUnitRows = new List<DataSetFSO.PRODUCT_UNITRow>();
                            productUnitRows.Clear();
                            productUnitRows = (from tmpRow in dataSetFSO1.PRODUCT_UNIT where (tmpRow.RowState != DataRowState.Deleted && tmpRow.CP_STAGE_ID == row.CP_STAGE_ID && tmpRow.NAME == row.NAME) select tmpRow).ToList();
                            productUnitRows.Reverse();

                            for (int i = 0; i < (0-dCount); i++)
                            {
                                DeleteInvoiceOutItems(productUnitRows[i].ID);
                                DeletePaymentInItems(productUnitRows[i].ID);
                                productUnitRows[i].Delete();
                            }   
                        
                        }
                        else if (dCount > 0)
                        {
                            for (int i = 0; i < dCount; i++)
                            {
                                DataSetFSO.PRODUCT_UNITRow tmpProduct = dataSetFSO1.PRODUCT_UNIT.NewPRODUCT_UNITRow();
                                tmpProduct.TYPE = row.TYPE;
                                tmpProduct.NAME = row.NAME;
                                tmpProduct.CP_STAGE_ID = row.CP_STAGE_ID;
                                tmpProduct.PID = _rowCalendarPlan.PID;
                                if (!row.IsNSI_PRODUCT_IDNull())
                                    tmpProduct.NSI_PRODUCT_ID = row.NSI_PRODUCT_ID;

                                dataSetFSO1.PRODUCT_UNIT.AddPRODUCT_UNITRow(tmpProduct);
                            }
                        }
                    }
                    else if (row.RowState == DataRowState.Deleted)
                    {
                        row.RejectChanges();
                        List<DataSetFSO.PRODUCT_UNITRow> productUnitRows = new List<DataSetFSO.PRODUCT_UNITRow>();
                        productUnitRows.Clear();
                        productUnitRows = (from tmpRow in dataSetFSO1.PRODUCT_UNIT where (tmpRow.RowState != DataRowState.Deleted && tmpRow.CP_STAGE_ID == row.CP_STAGE_ID && tmpRow.NAME == row.NAME) select tmpRow).ToList();                        
                        
                        foreach (DataSetFSO.PRODUCT_UNITRow delRowProductUnit in productUnitRows)
                        {
                            DeleteInvoiceOutItems(delRowProductUnit.ID);
                            DeletePaymentInItems(delRowProductUnit.ID);
                            delRowProductUnit.Delete();
                        }   
                     
                    }
                }
                resultInformation += "\n" + ModifiedInvoiceOut() + "\n" + ModifiedPaymentIn();
                if (countModifiedItems > 0)
                {
                    MessageBox.Show(this, resultInformation, "Внесение изменений", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                resultInformation = "";
                nRowsUpdatedCount += producT_UNITTableAdapter1.Update(dataSetFSO1.PRODUCT_UNIT);
                //nRowsUpdatedCount += invoicE_OUT_ITEMTableAdapter1.Update(dataSetFSO1.INVOICE_OUT_ITEM);
                //nRowsUpdatedCount += paymenT_IN_ITEMTableAdapter1.Update(dataSetFSO1.PAYMENT_IN_ITEM);

                _isNew = false;
                SetControlEnabled(true);
                /////////////////////////////////////
                radMenuGridView.Visible = false;
                DesignGridProduct(-1);
                /////////////////////////////////////
            }
            countModifiedItems = 0;
            RefreshForm();

            return nRowsUpdatedCount;
        }

        public int RefreshForm()
        {
            int result = 0;            
            
            //Перезаполнение всех этапов
            DesignTreeViewStages();           

            //Перезаполнение агрегированных данных товаров по этапам
            dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.Clear();

            producT_UNIT_BY_CPSTAGESTableAdapter1.ClearBeforeFill = false;
            foreach (DataSetFSO.CP_STAGERow row in dataSetFSO1.CP_STAGE)
            {
                producT_UNIT_BY_CPSTAGESTableAdapter1.FillbyCPStageId(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES, row.ID);
            }
            producT_UNIT_BY_CPSTAGESTableAdapter1.ClearBeforeFill = true;
            
            BindControlsClalendarPlan();
            
            return result;
        }

        public string FormName
        {
            get
            {
                string returnString = "CalendarPlan_";

                if (_isNew)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString + _rowCalendarPlan.ID;
                }
                return returnString;
            }
        }

        #endregion

        #region InterfaceObjDeleteableForm

        public int Delete()
        {
            int nRowsDeletedCount = -1;

            int countChildStages = (from rowsStages in dataSetFSO1.CP_STAGE where (rowsStages.RowState == DataRowState.Unchanged && rowsStages.CALENDAR_PLAN_ID == _rowCalendarPlan.ID) select rowsStages.ID).Count();

            if (_rowCalendarPlan != null && countChildStages > 0)
            {
                MessageBox.Show(this, "Невозможно удалить календарный план!", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                _rowCalendarPlan.Delete();
                nRowsDeletedCount = calendaR_PLANTableAdapter1.Update(_rowCalendarPlan);
                this.Close();
            }
            
            return nRowsDeletedCount;
        }

        #endregion

        #region Events

        //События работы с формой
        #region FormEvents

        private void FormCalendarPlan_Load(object sender, EventArgs e)
        {

            //Нумерация id-шников в датасете начная с -2
            dataSetFSO1.CP_STAGE.IDColumn.AutoIncrementSeed = -2;

            SetControlsVisible(false);

            if (_isNew)
            {
                SetControlEnabled(false);
            }
            radMenuGridView.Visible = false;
            if (!_isNew)
            {
                //Заполнение этапов по календарному плану
                cP_STAGETableAdapter1.FillByCalendarPlanId(dataSetFSO1.CP_STAGE, _rowCalendarPlan.ID);

                //Заполнение единиц продуктов по всем этапам
                producT_UNIT_BY_CPSTAGESTableAdapter1.ClearBeforeFill = false;
                foreach (DataSetFSO.CP_STAGERow row in dataSetFSO1.CP_STAGE)
                {
                    producT_UNIT_BY_CPSTAGESTableAdapter1.FillbyCPStageId(dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES, row.ID);
                }
                producT_UNIT_BY_CPSTAGESTableAdapter1.ClearBeforeFill = true;

            }

            DesignGridProduct(-1);
            DesignTreeViewStages();

            this.BindControlsClalendarPlan();

        }

        private void radLabelContract_DoubleClick(object sender, EventArgs e)
        {
            FormContract formContract = new FormContract(_rowCalendarPlan.CONTRACTRow);
            if (!FormHelper.HasOpenedForm(formContract.FormName))
            {
                formContract.MdiParent = FormHelper.MainForm;
                formContract.Show();
                formContract.Select();
            }
        }

        private void FormCalendarPlan_FormClosing(object sender, FormClosingEventArgs e)
        {
            int countModifiedObjects = 0;

            //Есть ли измененные этапы
            countModifiedObjects += (from rowCpStages in dataSetFSO1.CP_STAGE where (rowCpStages.RowState == DataRowState.Added || rowCpStages.RowState == DataRowState.Deleted || rowCpStages.RowState == DataRowState.Modified) select rowCpStages).Count();
            //Есть ли измененные единицы товаров или работ
            countModifiedObjects += (from rowProductUnitByStages in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (rowProductUnitByStages.RowState == DataRowState.Added || rowProductUnitByStages.RowState == DataRowState.Modified || rowProductUnitByStages.RowState == DataRowState.Deleted) select rowProductUnitByStages).Count();

			if (!AllowSave)
				return;

            if (_rowCalendarPlan.RowState != DataRowState.Deleted && _rowCalendarPlan.RowState != DataRowState.Detached &&(_rowCalendarPlan.RowState == DataRowState.Added || _rowCalendarPlan.RowState == DataRowState.Modified || countModifiedObjects > 0))
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true;
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.RejectChanges();
                    dataSetFSO1.CP_STAGE.RejectChanges();
                    _rowCalendarPlan.RejectChanges();
                }
            }

        }

        #endregion


        //События работы с деревом
        #region TreeViewEvents

        //Создание нового этапа
        private void radMenuItemCreateStage_Click(object sender, EventArgs e)
        {
            if (radTreeViewStages.SelectedNode != null)
            {
                if ((System.Int32)radTreeViewStages.SelectedNode.Tag == _RootNodeTag)
                {
                    dataSetFSO1.CP_STAGE.AddCP_STAGERow("Новый", "Новый Этап", DateTime.Now.Date, DateTime.Now.Date, _rowCalendarPlan, null, DateTime.Now, "", _rowCalendarPlan.PID);

                    while (radTreeViewStages.Nodes.Count > 1)
                    {
                        RadTreeNode tmp = radTreeViewStages.Nodes[0];
                        if ((System.Int32)tmp.Tag == _RootNodeTag)
                            tmp = radTreeViewStages.Nodes[1];
                        radTreeViewStages.SelectedNode.Nodes.Add(tmp);
                    }

                    foreach (RadTreeNode node in radTreeViewStages.SelectedNode.Nodes)
                    {
                        node.ImageIndex = 0;
                        node.SelectedImageIndex = 2;
                        node.StateImageIndex = 1;
                    }
                }
                else
                {
                    DataSetFSO.CP_STAGERow parentRow = (DataSetFSO.CP_STAGERow)((DataRowView)radTreeViewStages.SelectedNode.DataBoundItem).Row;
                    dataSetFSO1.CP_STAGE.AddCP_STAGERow("Новый", "Новый Этап", DateTime.Now.Date, DateTime.Now.Date, _rowCalendarPlan, parentRow, DateTime.Now, "", _rowCalendarPlan.PID);
                    radTreeViewStages.Update();

                    foreach (RadTreeNode node in radTreeViewStages.SelectedNode.Nodes)
                    {
                        node.ImageIndex = 0;
                        node.SelectedImageIndex = 2;
                        node.StateImageIndex = 1;
                    }
                }

                radTreeViewStages.SelectedNode.Expand();
            }
        }

        //Удаление этапа
        private void radMenuItemDeleteStage_Click(object sender, EventArgs e)
        {
            if ((System.Int32)radTreeViewStages.SelectedNode.Tag != _RootNodeTag)
            {
                DataSetFSO.CP_STAGERow selectedStage = (DataSetFSO.CP_STAGERow)((DataRowView)radTreeViewStages.SelectedNode.DataBoundItem).Row;
                int countChildStages = (from rowChildStages in dataSetFSO1.CP_STAGE where (rowChildStages.RowState != DataRowState.Deleted && rowChildStages.PARENT_STAGE_ID == selectedStage.ID) select rowChildStages.ID).Count();
                int countProductUnit = (from rowProductUnit in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (rowProductUnit.RowState != DataRowState.Deleted && rowProductUnit.CP_STAGE_ID == selectedStage.ID) select rowProductUnit).Count();
                if (countChildStages > 0 || countProductUnit > 0)
                {
                    MessageBox.Show(this, "Невозможно удалить этап", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    if (selectedStage.RowState == DataRowState.Added)
                    {
                        radTreeViewStages.SelectedNode.Remove();
                    }
                    selectedStage.Delete();
                }
            }
        }

        // Смена этапа (переход)
        private void radTreeViewStages_SelectedNodeChanged(object sender, RadTreeViewEventArgs e)
        {
            //MessageBox.Show("XXXXXX");
            RadTreeNode clickedNode = e.Node;
            if (clickedNode != null)
            {
                if ((System.Int32)clickedNode.Tag == _RootNodeTag)
                {
                    radMenuGridView.Visible = false;
                    SetControlsVisible(false);
                    DesignGridProduct((System.Int32)clickedNode.Tag);
                }
                else if (((DataSetFSO.CP_STAGERow)((DataRowView)clickedNode.DataBoundItem).Row).RowState == DataRowState.Added)
                {
                    radMenuGridView.Visible = false;
                    SetControlsVisible(true);
                    DesignGridProduct((System.Int32)clickedNode.Tag);
                    BindControlsCPStage();
                }
                else
                {
                    radMenuGridView.Visible = true;
                    SetControlsVisible(true);
                    DesignGridProduct((System.Int32)clickedNode.Tag);
                    BindControlsCPStage();
                }

            }
        }

        //Перевязка этапа
        private void radTreeViewStages_DragEnding(object sender, RadTreeViewDragCancelEventArgs e)
        {
            DataSetFSO.CP_STAGERow Node = (DataSetFSO.CP_STAGERow)((DataRowView)e.Node.DataBoundItem).Row;

            if ((System.Int32)e.TargetNode.Tag != _RootNodeTag)
            {
                DataSetFSO.CP_STAGERow TargetNode = (DataSetFSO.CP_STAGERow)((DataRowView)e.TargetNode.DataBoundItem).Row;
                Node.PARENT_STAGE_ID = TargetNode.ID;
            }
            else
            {
                Node.SetPARENT_STAGE_IDNull();
            }
        }

        //Смена имени этапа
        private void radTreeViewStages_DoubleClick(object sender, EventArgs e)
        {
            MouseEventArgs args = e as MouseEventArgs;
            RadTreeNode clickedNode = radTreeViewStages.GetNodeAt(args.X, args.Y);
            if (clickedNode != null && (System.Int32)clickedNode.Tag != _RootNodeTag)
            {
                radTreeViewStages.BeginEdit();
            }
        }

        //Раскрыть всё дерево этапов
        //private void radMenuItemExpandAll_Click(object sender, EventArgs e)
        //{
        //    radTreeViewStages.ExpandAll();
        //}

        #endregion


        //События для работы с таблицей товаров
        #region GridProductUnitEvents

        //Добавление единицы товара
        private void radMenuItemAddProduct_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject form = new DialogFormSelectObject(ObjctTypeEnum.NSI_PRODUCT);
            if (form.ShowDialog() == DialogResult.OK)
            {
                foreach (GridViewRowInfo rowInf in form.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.NSI_PRODUCTRow)
                    {
                        DataSetFSO.NSI_PRODUCTRow productRow = drv.Row as DataSetFSO.NSI_PRODUCTRow;

                        //Проверяем был ли добавлен Товар к календарному плану
                        if ((from row in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (row.RowState != DataRowState.Deleted && row.CP_STAGE_ID == (System.Int32)radTreeViewStages.SelectedNode.Tag && row.NSI_PRODUCT_ID == productRow.ID) select row).Count() > 0)
                        {
                            MessageBox.Show("Данный товар уже добавлен к выбранному этапу!");
                        }
                        else
                        {
                            DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow rowNewProd = dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NewPRODUCT_UNIT_BY_CPSTAGESRow();
                            dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.AddPRODUCT_UNIT_BY_CPSTAGESRow(rowNewProd);
                            rowNewProd.NSI_PRODUCT_ID = productRow.ID;
                            rowNewProd.CP_STAGE_ID = (System.Int32)radTreeViewStages.SelectedNode.Tag;
                            rowNewProd.COUNT = 1;
                            if (!productRow.IsNSI_METER_NAMENull())
                                rowNewProd.NSI_METER_NAME = productRow.NSI_METER_NAME;
                            //if (!productRow.IsSHORT_NAMENull())
                            rowNewProd.NAME = productRow.SHORT_NAME;
                            rowNewProd.TYPE = true;
                        }
                    }
                }
            }
        }

        //Создание работы
        private void radMenuItemAddWork_Click(object sender, EventArgs e)
        {
            DialogFormAddNewWork dialog = new DialogFormAddNewWork();
            dialog.ShowDialog();
            if (dialog.DialogResult == DialogResult.OK)
            {
                if (dialog.WorkName.Length > 0)
                {
                    if ((from row in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (row.RowState != DataRowState.Deleted && row.CP_STAGE_ID == (System.Int32)radTreeViewStages.SelectedNode.Tag && row.NAME == dialog.WorkName && row.TYPE == false) select row).Count() > 0)
                    {
                        MessageBox.Show("Данная работа уже добавлена к выбранному этапу!");
                    }
                    else
                    {
                        DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow rowNewProd = dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NewPRODUCT_UNIT_BY_CPSTAGESRow();
                        dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.AddPRODUCT_UNIT_BY_CPSTAGESRow(rowNewProd);                        
                        rowNewProd.CP_STAGE_ID = (System.Int32)radTreeViewStages.SelectedNode.Tag;
                        rowNewProd.COUNT = 1;
                        rowNewProd.NAME = dialog.WorkName;                        
                        rowNewProd.TYPE = false;
                        //Для работ NSI_PRODUCT сделаем -1
                        rowNewProd.NSI_PRODUCT_ID = -1;
                    }
                }
                else
                {
                    MessageBox.Show(this, "Вы не ввели наименование работы. Данная работа не может быть добавлена.", "Пустое имя", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        //Удаление единицы продукта (товара или работы)
        private void radMenuItemDeleteProductUnit_Click(object sender, EventArgs e)
        {
            string textError = "Невозможно удалить:";

            bool isCanDel = true;

            if (radGridViewProducts.SelectedRows.Count > 0)
            {

                GridViewRowInfo rowInf = radGridViewProducts.SelectedRows.First();
                DataRowView drv = (DataRowView)rowInf.DataBoundItem;

                if (drv != null && drv.Row is DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow)
                {
                    DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow delRow = (DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow)drv.Row;

                    dataSetFSO1.PRODUCT_UNIT.Clear();
                    producT_UNITTableAdapter1.FillByCPStageID(dataSetFSO1.PRODUCT_UNIT, delRow.CP_STAGE_ID);

                    List<DataSetFSO.PRODUCT_UNITRow> productUnitRows = new List<DataSetFSO.PRODUCT_UNITRow>();
                    productUnitRows.Clear();

                    productUnitRows = (from prodUnitRow in dataSetFSO1.PRODUCT_UNIT where (prodUnitRow.RowState != DataRowState.Deleted && prodUnitRow.CP_STAGE_ID == delRow.CP_STAGE_ID && prodUnitRow.NAME == delRow.NAME) select prodUnitRow).ToList();

                    int countDel = 0;

                    foreach (DataSetFSO.PRODUCT_UNITRow delRowProductUnit in productUnitRows)
                    {
                        if (!delRowProductUnit.IsVAT_INVOICE_IDNull())
                        {
                            isCanDel = false;
                            countDel++;
                        }
                        
                    }

                    string stageNumber = (from stgRow in dataSetFSO1.CP_STAGE where stgRow.ID == delRow.CP_STAGE_ID select stgRow.NUMBER).First();

                    if (countDel > 0)
                    {
                        textError += "\n" + countDel + " " + delRow.NAME + " из этапа № " + stageNumber;
                    }

                    if (isCanDel)
                    {                        
                        delRow.Delete();
                    }
                    else
                    {
                        MessageBox.Show(this, textError, "Ошибки удаления", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                dataSetFSO1.PRODUCT_UNIT.Clear();
            }
        }
           
        //Изменение количество товара или работы
        private void radGridViewProducts_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            bool isCanModify = true;

            string textError = "Невозможно удалить:";

            GridViewRowInfo rowInf = e.Row;
            DataRowView drv = (DataRowView)rowInf.DataBoundItem;

            if (drv != null && drv.Row is DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow)           
            {
                DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow modifiedRow = (DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow)drv.Row;

                if (modifiedRow.RowState != DataRowState.Added)
                {
                    dataSetFSO1.PRODUCT_UNIT.Clear();
                    producT_UNITTableAdapter1.FillByCPStageID(dataSetFSO1.PRODUCT_UNIT, modifiedRow.CP_STAGE_ID);

                    int newCount = modifiedRow.COUNT;

                    List<DataSetFSO.PRODUCT_UNITRow> productUnitRows = new List<DataSetFSO.PRODUCT_UNITRow>();
                    productUnitRows.Clear();

                    productUnitRows = (from prodUnitRow in dataSetFSO1.PRODUCT_UNIT where (prodUnitRow.RowState != DataRowState.Deleted && prodUnitRow.CP_STAGE_ID == modifiedRow.CP_STAGE_ID && prodUnitRow.NAME == modifiedRow.NAME) select prodUnitRow).ToList();
                    productUnitRows.Reverse();

                    int oldCount = productUnitRows.Count();

                    int dCount = newCount - oldCount;
                    
                    if (dCount < 0)
                    {         

                        int countDel = 0;

                        for (int i = 0; i > dCount; i--)
                        {
                            if (!productUnitRows[0 - i].IsVAT_INVOICE_IDNull())
                            {
                                isCanModify = false;
                                countDel++;
                            }
                        }

                        string stageNumber = (from stgRow in dataSetFSO1.CP_STAGE where stgRow.ID == modifiedRow.CP_STAGE_ID select stgRow.NUMBER).First();

                        if (countDel > 0)
                        {
                            textError += "\n" + countDel + " " + modifiedRow.NAME + " из этапа № " + stageNumber;
                        }

                        if (isCanModify)
                        {
                            modifiedRow.COUNT = newCount;
                        }
                        else
                        {
                            MessageBox.Show(this, textError, "Ошибки удаления", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            modifiedRow.COUNT = oldCount;
                        }

                    }
                    else
                    {
                        modifiedRow.COUNT = newCount;
                    }
                }
            }
        }
        
        //Добавление продуктов из другого этапа
        private void radMenuItemMoveProducts_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectProd = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _rowCalendarPlan.PID);
            if (selectProd.ShowDialog() == DialogResult.OK)
            {
                DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow prUnitRow;
                DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow newPrUnitByCpStageRow;
                DataSetFSO.PRODUCT_UNIT_BY_CPSTAGESRow oldPrUnitByCpStageRow;
                DataSetFSO.PRODUCT_UNITRow modifiedPrUnitRow;
                foreach (GridViewRowInfo rowInf in selectProd.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow)
                    {
                        prUnitRow = drv.Row as DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow;
                        oldPrUnitByCpStageRow = (from row in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (row.RowState != DataRowState.Deleted && row.CP_STAGE_ID == prUnitRow.CP_STAGE_ID && row.NAME == prUnitRow.NAME && row.NSI_PRODUCT_ID == row.NSI_PRODUCT_ID) select row).FirstOrDefault();
                        newPrUnitByCpStageRow = (from row in dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES where (row.RowState != DataRowState.Deleted && row.CP_STAGE_ID == (System.Int32)radTreeViewStages.SelectedNode.Tag && row.NAME == prUnitRow.NAME && row.TYPE == prUnitRow.TYPE && row.NSI_PRODUCT_ID == prUnitRow.NSI_PRODUCT_ID) select row).FirstOrDefault();
                        modifiedPrUnitRow = producT_UNITTableAdapter1.GetDataByID(prUnitRow.ID).FindByID(prUnitRow.ID);

                        if (newPrUnitByCpStageRow != null)
                        {                            
                            newPrUnitByCpStageRow.COUNT++;                           
                        }
                        else
                        {
                            newPrUnitByCpStageRow = dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.NewPRODUCT_UNIT_BY_CPSTAGESRow();
                            dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.AddPRODUCT_UNIT_BY_CPSTAGESRow(newPrUnitByCpStageRow);
                            newPrUnitByCpStageRow.NSI_PRODUCT_ID = modifiedPrUnitRow.NSI_PRODUCT_ID;
                            newPrUnitByCpStageRow.CP_STAGE_ID = (System.Int32)radTreeViewStages.SelectedNode.Tag;
                            newPrUnitByCpStageRow.COUNT = 1;
                            if (!prUnitRow.IsNSI_METER_NAMENull())
                                newPrUnitByCpStageRow.NSI_METER_NAME = prUnitRow.NSI_METER_NAME;
                            newPrUnitByCpStageRow.NAME = prUnitRow.NAME;
                            newPrUnitByCpStageRow.TYPE = prUnitRow.TYPE;

                            //newPrUnitByCpStageRow.AcceptChanges();
                        }

                        oldPrUnitByCpStageRow.COUNT--;
                        if (oldPrUnitByCpStageRow.COUNT <= 0)
                        {
                            oldPrUnitByCpStageRow.Delete();
                        }

                        modifiedPrUnitRow.CP_STAGE_ID = newPrUnitByCpStageRow.CP_STAGE_ID;

                        producT_UNITTableAdapter1.Update(modifiedPrUnitRow);
                    }
                }
                dataSetFSO1.PRODUCT_UNIT_BY_CPSTAGES.AcceptChanges();    
            }
        }
        #endregion
        #endregion

    }  

}
